package org.wujiangbo.service.impl;

import org.wujiangbo.service.RedisService;
import org.wujiangbo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisService redisService;

    @Override
    public String createToken() {
        String uuid = UUID.randomUUID().toString();
        //存入Redis的key添加一个统一前缀字符串
        String token = "mideng_check:" + uuid;
        //存入Redis
        boolean result = redisService.setEx(token, uuid, 10000L);
        if(result){
            return token;
        }
        return null;
    }

    //接口幂等校验核心逻辑
    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {
        //从请求头中获取token的值
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            //请求头中不存在token，那就是非法请求，直接抛出异常
            throw new Exception("Illegal request");
        }
        if (!redisService.exists(token)) {
            //请求头中存在token，但是Redis中不存在的话，也抛出异常
            throw new Exception("token error");
        }
        //代码执行到这里，说明token校验成功了，那么就需要删除Redis中的值
        boolean remove = redisService.remove(token);
        if (!remove) {
            //删除失败了
            throw new Exception("token delete error");
        }
        return true;
    }
}